﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.IO;


namespace Billing2
{
    public class Global : HttpApplication
    {
        //static public string Referrer = "";
        public static Checker checker = null;
        static Dictionary<string, UserLoginData> m_UserLoginLog = null;

        protected void Application_Start(object sender, EventArgs e)
        {
            EPPLog.Logger.SetPath(HttpContext.Current.Server.MapPath(@"\") + @"log" + Path.DirectorySeparatorChar.ToString());

            ClsApplicationConfiguration.setConfigure();
            DBLibrary.DBFactory.InitConnectString(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            //string Referrer = GetRootURI();
            //EPPLog.Logger.Debug("EPP root URI is '{0}'.", Referrer);

            m_UserLoginLog = new Dictionary<string, UserLoginData>();

            //DBCommands2 db = new DBCommands2(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            //string s = db.SelectString("select top 1 assetid from subscriber where assetid like '%?'");
            //byte[] arr = System.Text.UnicodeEncoding.Default.GetBytes(s);
            //string ss = ClsPasswordHelper.Encrypt("admin");
            //EPPLog.Logger.Debug(ss);

            try
            {
                checker = new Checker();
                checker.Start();
                EPPLog.Logger.Info("AsyncTask.Checker started.");

                LoadCommonPWList();

                //checker.LockMonth(2016, 9);
                test();                
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error(ex);
            }
        }


        static SortedList<string, string> CommonPWList = new SortedList<string, string>();

        static void LoadCommonPWList()
        {
            string filename = ClsApplicationConfiguration.CommonPasswordListFileName;
            
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            while (true)
            {
                string s = sr.ReadLine();
                if (s == null)
                    break;
                s = s.Trim();
                if (s == "")
                    continue;
                if (CommonPWList.ContainsKey(s))
                    continue;
                CommonPWList.Add(s, "");
            }
            sr.Close();
            fs.Close();
        }

        static public bool IsCommonPW(string pw)
        {
            return CommonPWList.ContainsKey(pw);
        }

       
        static public UserLoginData FindLoginLog(string _username)
        {
            string username = _username.ToUpper();
            if (!m_UserLoginLog.ContainsKey(username))
            {
                EPPLog.Logger.Debug("m_UserLoginLog.ContainsKey add key: {0}", username);
                UserLoginData data = new UserLoginData();
                data.username = username;
                data.retry = 1;
                data.last_login = DateTime.Now;
                data.session_id = "";
                m_UserLoginLog.Add(username, data);
            }
            return m_UserLoginLog[username];
        }

        static void test()
        {
            //string s1 = ClsPasswordHelper.Encrypt("admin");
            //string s2 = ClsPasswordHelper.Decrypt("idqJihpqiYlaf6YmLm9H0A==");
            //EPPLog.Logger.Info(string.Format("test: s1='{0}' s2='{1}'", s1, s2));
        }

        //static string GetRootURI()
        //{
        //    string AppPath = "";
        //    HttpContext HttpCurrent = HttpContext.Current;
        //    HttpRequest Req;
        //    if (HttpCurrent != null)
        //    {
        //        Req = HttpCurrent.Request;
        //        string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
        //        if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
        //            //install at root
        //            AppPath = UrlAuthority + "/";
        //        else
        //            //install at virtual folder
        //            AppPath = UrlAuthority + Req.ApplicationPath;
        //    }
        //    return AppPath;
        //}

        protected void Session_Start(object sender, EventArgs e)
        {
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                Exception ex = Server.GetLastError();
                if (ex != null && ex.Message == "File does not exist.")
                {
                    EPPLog.Logger.Error("File does not exist: " + Common.EscapeLog(HttpContext.Current.Request.Url.ToString()));
                }
                if (ex != null)
                    EPPLog.Logger.Error(String.Format("Application_Error:\r\n\tType={0}\r\n\tMessage={1}\r\n\tInnerException={2}\r\n\tTrace={3}"
                        , ex.GetType()
                        , ex.Message
                        , ex.InnerException == null ? "" : ex.InnerException.Message
                        , ex.StackTrace));
                else
                    EPPLog.Logger.Error("Application_Error, Unknown. " + e.ToString());
            }
            catch (Exception ex2)
            {
                EPPLog.Logger.Error("Application_Error. Unexpected error. " + ex2.Message);
            }

            try
            {
                Response.Redirect("default.aspx", false);
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error(ex.Message);
            }
        }

        protected void Session_End(object sender, EventArgs e)
        {
            this.Session.Clear();
            //this.Response.Redirect("default.aspx");
        }

        protected void Application_End(object sender, EventArgs e)
        {
        }

        public static bool IsAllowDomain(string referrer)
        {
            string[] list = ClsApplicationConfiguration.AllowDomain.ToLower().Split(new char[]{','});
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i].Trim() == "")
                    continue;
                if (MyLib.Utility.LeftCompare(referrer, list[i].Trim()))
                    return true;
            }
            return false;
        }
    }

    public class UserLoginData
    {
        public string username;
        public DateTime last_login;
        public int retry;
        public string session_id;

        public UserLoginData()
        {
            this.username = "";
            this.last_login = DateTime.MinValue;
            this.retry = 0;
            this.session_id = "";
        }
    }
}